﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel;
using Microsoft.Crm.Workflow;
using System.Workflow.ComponentModel.Compiler;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;

namespace CrmContrib.Workflow.Activities.Marketing
{
    [CrmWorkflowActivity("Close a lead", "CrmContrib \\ Marketing")]
    public class CloseLeadActivity : Activity
    {
        [CrmInput("Lead")]
        [CrmReferenceTarget("lead")]
        [ValidationOption(ValidationOption.Required)]
        public Lookup Lead
        {
            get { return (Lookup)base.GetValue(CloseLeadActivity.LeadProperty); }
            set { base.SetValue(CloseLeadActivity.LeadProperty, value); }
        }

        public static readonly DependencyProperty LeadProperty = DependencyProperty.Register("Lead", typeof(Lookup), typeof(CloseLeadActivity));

        // TODO : switch leadstatus to a picklist so that when creating the workflow the disqualification status can be specified

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            var contextService = executionContext.GetService<IContextService>();
            var workflowContext = contextService.Context;
            var crmService = workflowContext.CreateCrmService();
            
            SetStateLeadRequest closeLead = new SetStateLeadRequest();
            closeLead.EntityId = Lead.Value;
            closeLead.LeadState = LeadState.Disqualified;
            closeLead.LeadStatus = 7; // cancelled

            // values for lead status can be:
            // 4 = lost
            // 5 = cannot contact
            // 6 = no longer interested
            // 7 = cancelled


            SetStateLeadResponse stateSet = (SetStateLeadResponse)crmService.Execute(closeLead);

            return base.Execute(executionContext);
        }
    }
}
    